﻿/********************************************************************************

** 作   者： litao

** 创始时间： 2012-08-29

** 作用描述： 主要用于ini配置文件的读取和写入

*********************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server
{
    public class ReaderWriter
    {
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="FlieName">文件名称</param>
        /// <param name="NodeName">文件主节点名称</param>
        /// <param name="FlieNode">节点名称</param>
        /// <param name="FlieMessage">写入内容</param>
        public static void WriteIni(string FlieName, string FlieNode, string NodeName, string FlieMessage)
        {
            WritePrivateProfileString(FlieNode, NodeName, FlieMessage, Application.StartupPath + "\\" + FlieName + ".ini");
        }

        /// <summary>
        /// 读取ini文件
        /// </summary>
        /// <param name="FlieName">文件名称</param>
        /// <param name="FlieNode">文件主节点名称</param>
        /// <param name="NodeName">节点名称</param>
        /// <returns>读取到的节点内容</returns>
        public static string ReadIni(string FlieName, string FlieNode, string NodeName)
        {
            StringBuilder message = new StringBuilder();
            GetPrivateProfileString(FlieNode, NodeName, "", message, 500, Application.StartupPath + "\\" + FlieName + ".ini");
            return message.ToString();
        }

        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="section">配置节点名称</param>
        /// <param name="key">键名</param>
        /// <param name="val">键值</param>
        /// <param name="filePath">路径</param>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="section">配置节点名称</param>
        /// <param name="key">键名</param>
        /// <param name="def">值</param>
        /// <param name="size">每次从ini中读取多少字节</param>
        /// <param name="filePath">路径</param>
        /// <returns>返回读取数据</returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
   
    }
}
